<?php

declare(strict_types=1);

namespace cosy\framework\command\curd;

use cosy\framework\command\BaseMake;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Db;

/**
 * ClassName Model
 * Description TODO
 * Author BTC
 * Date 2023/11/3 18:28
 **/
class Model extends BaseMake
{
    protected $type = 'model';

    public function configure()
    {
        $this->setName('cosy:model')
            ->addArgument('module', Argument::REQUIRED, 'Please input your class name')
            ->addArgument('table', Argument::REQUIRED, 'Please input your table name')
            ->setDescription('创建一个model模型');
    }

    protected function execute(Input $input, Output $output)
    {
        $table = trim($input->getArgument('table'));
        $tableName = substr($table, strlen(env('DB_PREFIX')));
        $array = explode('_', $tableName);
        foreach ($array as $key => $val){
            $array[$key] = ucfirst($val);
        }
        $mapper = implode('', $array);

        $module = trim($input->getArgument('module'));
        $name = 'app\\' . $module . '\\' . $this->type . '\\' . $mapper;

        $this->build($name, $table);
//        $this->executeBuild($input, $output);
    }

    // 填充模板
    public function build($name, $table)
    {
        $stub = $this->getStub();
        $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');

        $class = str_replace($namespace . '\\', '', $name);

        $className = $class . ucfirst($this->type);

        $tableName = $this->input->getArgument('table');
        $res = Db::query("show full COLUMNS FROM $tableName");
        foreach ($res as $key => $val){
            if($val['Extra'] == 'auto_increment'){
                $pk = $val['Field'];
                break;
            }
        }
        $prefix_num = strlen(config('database.connections.mysql.prefix'));
        $tableName = substr($tableName,$prefix_num);

        $columns = Db::table($table)->getFields();
        $types = Db::table($table)->getFieldsType();
        $property = "";
        $schema = '';
        foreach ($columns as $key => $column){
            if($column['name'] == end($columns)['name']){
                $property = $property . ' * @property ' . $types[$key] . ' $' . $column['name'] . ' ' . $column['comment'];
                $schema = $schema . "        '" . $column['name'] . "' => '" . $types[$key] . "'" ;
            }else{
                $property = $property . ' * @property ' . $types[$key] . ' $' . $column['name'] . ' ' . $column['comment'] . PHP_EOL;
                $schema = $schema . "        '" . $column['name'] . "' => '" . $types[$key] . "'," . PHP_EOL;
            }
        }

        $search = [
            '{%createTime%}',
            '{%className%}',
            '{%namespace%}',
            '{%tableName%}',
            '{%pk%}',
            '{%property%}',
            '{%schema%}'
        ];

        $replace = [
            date('Y-m-d H:i'),
            $className,
            $namespace,
            $tableName,
            $pk,
            $property,
            $schema
        ];

        file_put_contents($this->getPathName($name), str_replace($search, $replace, $stub));

        return true;
    }

    /**
     * 获取模板
     * @return string
     */
    protected function getStub()
    {
        $path = __DIR__.DIRECTORY_SEPARATOR.'stubs'.DIRECTORY_SEPARATOR.$this->type.'.stub';
        return file_get_contents($path);
    }

    protected function getPathName(string $name): string
    {
        $name = str_replace('app\\', '', $name);
        $name = $name . ucfirst($this->type);

        return $this->app->getBasePath() . ltrim(str_replace('\\', '/', $name), '/') . '.php';
    }
}